package com.xm.xmds1705083.service.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xm.xm.dto.ResultDto;
import com.xm.xm.dto.SearchDto;
import com.xm.xm.util.DateUtils;
import com.xm.xm.util.ErrorCode;
import com.xm.xm.util.ValidateUtils;
import com.xm.xmds1705083.service.dto.DuoduoBookingDto;
import com.xm.xmds1705083.service.dto.DuoduoParkDto;
import com.xm.xmds1705083.service.mapper.DuoduoBookingMapper;
import com.xm.xmds1705083.service.mapper.DuoduoParkMapper;
import com.xm.xmds1705083.service.mapper.DuoduoParkSpaceMapper;
import com.xm.xmds1705083.service.mapper.DuoduoSmsMapper;
import com.xm.xmds1705083.service.model.DuoduoBooking;
import com.xm.xmds1705083.service.model.DuoduoPark;
import com.xm.xmds1705083.service.model.DuoduoParkSpace;
import com.xm.xmds1705083.service.model.DuoduoSms;
import com.xm.xmds1705083.service.service.DuoduoBookingService;
import com.xm.xmds1705083.service.util.GlobalError;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 杭州新苗网络科技有限公司
 *
 * @author meihf
 * @date 2017/06/14
 * @description
 */
@Service("duoduoBookingService")
public class DuoduoBookingServiceImpl extends ServiceImpl<DuoduoBookingMapper, DuoduoBooking> implements DuoduoBookingService {

    @Autowired
    DuoduoBookingMapper duoduoBookingMapper;

    @Autowired
    DuoduoSmsMapper duoduoSmsMapper;

    @Autowired
    DuoduoParkMapper duoduoParkMapper;

    @Autowired
    DuoduoParkSpaceMapper duoduoParkSpaceMapper;

    @Override
    public ResultDto selectBookingList(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        searchDto.setPageNo((searchDto.getPageNo() - 1) * searchDto.getPageSize());
        try {
            List<DuoduoParkDto> duoduoBookingDtos = duoduoBookingMapper.selectBookingList(searchDto);
            if (duoduoBookingDtos.size() == 0) {
                resultDto.setCode(ErrorCode.C11001);
                resultDto.setMsg(ErrorCode.E11001);
                return resultDto;
            }
            resultDto.setData(duoduoBookingDtos);
            resultDto.setMsg("查询成功！");
        } catch (RuntimeException e) {
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }


    @Override
    public ResultDto toBooking(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo() - 1) * searchDto.getPageSize());
        try {
            //验证码验证
            ResultDto result = checkSMS(searchDto);
            if (result.getCode()!=0){
                return result;
            }
            int parkId = filed.getInt("parkId");
            //查询在停车场有没有有效的预约情况 避免join进行多次查询
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.where(" userId={2} and parkId={0} and endTime>{1} ",parkId,searchDto.getTime(),searchDto.getAppUserId());
            int selectResult = duoduoBookingMapper.selectCount(entityWrapper);
            if (ValidateUtils.isGreaterThan0(selectResult)){
                resultDto.setMsg(GlobalError.E11021);
                resultDto.setCode(GlobalError.C11021);
            }else {
                //保存进入表里 先随机分配一个车位号
                List<DuoduoParkSpace> duoduoParkSpaceList = duoduoParkSpaceMapper.selectList(new EntityWrapper<DuoduoParkSpace>().where(" parkId={0}",parkId));
                if (duoduoParkSpaceList.size()==0){
                    resultDto.setCode(GlobalError.C11022);
                    resultDto.setMsg(GlobalError.E11022);
                    return resultDto;
                }
                Collections.shuffle(duoduoParkSpaceList);
                int parkingSpaceId = duoduoParkSpaceList.get(0).getId();
                filed.remove("validateCode");
                filed.remove("sendtype");
                DuoduoBooking duoduoBooking = (DuoduoBooking) JSONObject.toBean(filed,DuoduoBooking.class);
                duoduoBooking.setBookingTime(searchDto.getTime().intValue());
                duoduoBooking.setUserId(searchDto.getAppUserId());
                duoduoBooking.setParkingSpaceId(parkingSpaceId);
                duoduoBooking.setEndTime(duoduoBooking.getBookingTime()+3600);
                int insertResult = duoduoBookingMapper.insert(duoduoBooking);
                if (ValidateUtils.isGreaterThan0(insertResult)){
                    resultDto.setMsg("预约成功");
/*
                    EntityWrapper entityWrapper1 = new EntityWrapper();
                    entityWrapper1.where(" id={0}",parkId);
                    List<DuoduoPark>listparks = duoduoParkMapper.selectList(entityWrapper1);
                    if (listparks.size()==0) {
                        resultDto.setCode(ErrorCode.C11001);
                        resultDto.setMsg(ErrorCode.E11001);
                    }else{
                        int surplusSpace = listparks.get(0).getSurplusSpace()-1;
                        DuoduoPark duoduoParks = new DuoduoPark();
                        duoduoParks.setSurplusSpace(surplusSpace);
                        int updateResult= duoduoParkMapper.update(duoduoParks,entityWrapper1);
                        if (ValidateUtils.isGreaterThan0(updateResult)){
                            resultDto.setMsg("预约成功,车位修改更新成功");
                        }else {
                            resultDto.setMsg(ErrorCode.E11003);
                            resultDto.setCode(ErrorCode.C11003);
                        }

                    }*/


                }else {
                    resultDto.setMsg(ErrorCode.E11004);
                    resultDto.setCode(ErrorCode.C11004);
                }
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }

    public ResultDto checkSMS(SearchDto searchDto) {
        ReentrantLock lock = new ReentrantLock();
        lock.lock();
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        try {
            if (!filed.has("phone") || !filed.has("sendtype") || !filed.has("validateCode")) {
                resultDto.setMsg(ErrorCode.E10011);
                resultDto.setCode(ErrorCode.C10011);
                return resultDto;
            }
            long phone = filed.getLong("phone");
            int sendtype = filed.getInt("sendtype");
            int validateCode = filed.getInt("validateCode");
            if (!ValidateUtils.isMobileNO(phone)) {
                resultDto.setCode(ErrorCode.C10004);
                resultDto.setMsg(ErrorCode.E10004);
                return resultDto;
            }
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.where(" mobile = {0}  and sendtype = {1}  ", phone,
                    sendtype
            );
            entityWrapper.orderBy("validity", false);
            List<DuoduoSms> messageList = duoduoSmsMapper.selectList(entityWrapper);
            if (messageList.isEmpty()) {
                resultDto.setCode(ErrorCode.C10006);
                resultDto.setMsg(ErrorCode.E10006);
                return resultDto;
            }

            DuoduoSms sms = messageList.get(0);
            if (sms.getCheckcode().intValue() != validateCode) {
                resultDto.setCode(ErrorCode.C10006);
                resultDto.setMsg(ErrorCode.E10006);
                return resultDto;
            }
            if (DateUtils.getTimeSecondLong() > sms.getValidity()) {
                resultDto.setCode(ErrorCode.C10007);
                resultDto.setMsg(ErrorCode.E10007);
                return resultDto;
            }
            resultDto.setMsg("校验通过");
        } finally {
            lock.unlock();
        }
        return resultDto;
    }

    @Override
    public ResultDto cancelBooking(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo() - 1) * searchDto.getPageSize());
        try {
            if (!filed.has("parkId")) {
                resultDto.setMsg(ErrorCode.E10011);
                resultDto.setCode(ErrorCode.C10011);
                return resultDto;
            }

            int parkId = filed.getInt("parkId");
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.where(" parkId={0}  and userId={1} and endTime>{2} ",parkId,searchDto.getAppUserId(),searchDto.getTime());
            int duoduoPark = duoduoBookingMapper.delete(entityWrapper);

            if (ValidateUtils.isGreaterThan0(duoduoPark)){
                resultDto.setMsg("取消预约成功");

               /* EntityWrapper entityWrapper1 = new EntityWrapper();
                entityWrapper1.where(" id={0}",parkId);
                List<DuoduoPark>listparks = duoduoParkMapper.selectList(entityWrapper1);
           // if (listparks.size()==0) {
                resultDto.setCode(ErrorCode.C11001);
                resultDto.setMsg(ErrorCode.E11001);
            }else{
                int surplusSpace = listparks.get(0).getSurplusSpace()+1;
                DuoduoPark duoduoParks = new DuoduoPark();
                duoduoParks.setSurplusSpace(surplusSpace);
               int updateResult= duoduoParkMapper.update(duoduoParks,entityWrapper1);
                if (ValidateUtils.isGreaterThan0(updateResult)){
                    resultDto.setMsg("取消预约成功,车位修改更新成功");
                }else {
                    resultDto.setMsg(ErrorCode.E11003);
                    resultDto.setCode(ErrorCode.C11003);
                }
            }*/
            }else {
                resultDto.setCode(ErrorCode.C11002);
                resultDto.setMsg(ErrorCode.E11002);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }

        return resultDto;

    }
}

